<template>
  <div>
    <modify-dialog-comp 
      v-if="showDialog" 
      :show-child-dialog.sync="showDialog"
      :testCaseTagsM="testCaseTags"
      :testCaseVersionM="testCaseVersion"
      :dataM="modifyData"
      @modifyFlush="flushTable"
      ref="dialog"
      >
    </modify-dialog-comp>
    <add-dialog-comp 
      v-if="showDialogAdd" 
      :show-child-dialog-add.sync="showDialogAdd" 
      :testCaseTags="testCaseTags"
      :testCaseVersion="testCaseVersion"
      @addFlush="flushTable"
      ref="dialogadd"
      >
    </add-dialog-comp>
    <run-dialog-comp 
      v-if="showDialogRun" 
      :show-child-dialog-run.sync="showDialogRun"
      @runFlush="flushTable"
      ref="dialogrun"
      >
    </run-dialog-comp>
    <view-dialog-comp v-if="showDialogView" ref="dialogview" :show-child-dialog-view.sync="showDialogView"></view-dialog-comp>
    <test-plan-dialog-comp 
      v-if="showDialogTestplan" 
      ref="dialogtestplan" 
      :show-child-dialog-testplan.sync="showDialogTestplan"
      >
    </test-plan-dialog-comp>
    <t-form
      ref="form"
      :data="formData"
      :label-width="80"
      colon
      @reset="onReset"
      @submit="onSubmit"
      :style="{ marginBottom: '8px' }"
    >
    <icon slot="op-column" name="descending-order" />
      <t-row style="margin-top: 20px;">
        <t-col :span="10">
          <t-row :gutter="[16, 24]">
            <t-col :flex="1">
              <t-form-item label="用例ID" name="id">
                <t-input
                  v-model="formData.testcase_id"
                  class="form-item-content"
                  type="search"
                  placeholder="请输入用例ID"
                  :style="{ minWidth: '134px' }"
                />
              </t-form-item>
            </t-col>
            <t-col :flex="1">
              <t-form-item label="用例名" name="name">
                <t-input
                  v-model="formData.testcase_name"
                  class="form-item-content"
                  type="search"
                  placeholder="请输入用例名"
                  :style="{ minWidth: '134px' }"
                />
              </t-form-item>
            </t-col>
            
            <t-col :flex="1">
              <t-form-item label="模块" name="module">
                <t-select
                  v-model="formData.module"
                  class="form-item-content"
                  placeholder="请选择模块"
                  :options="MODULES_OPTIONS"
                  multiple
                  @change="handleChangeModule"
                  id="module"
                  :style="{ minWidth: '134px' }"
                />               
              </t-form-item>
            </t-col>
            <t-col :flex="1">
              <t-form-item label="版本" name="version">
                <t-select
                  v-model="formData.testcase_version"
                  class="form-item-content"
                  placeholder="请选择版本"
                  @focus="getTestCaseVersion"
                  :options="testCaseVersion"
                  :keys="{ label: 'sprint_name', value: 'sprint_id' }"
                  multiple
                  @change="handleChangeVersion"
                  id="version"
                  :style="{ minWidth: '134px' }"
                />               
              </t-form-item>
            </t-col>
            <t-col :flex="1">
              <t-form-item label="优先级" name="priority">
                <t-select
                  v-model="formData.priority"
                  class="form-item-content"
                  placeholder="请选择优先级"
                  :options="TESTCASE_PRIORITY_OPTIONS"
                  multiple
                  @change="handleChangePriority"
                  id="priority"
                  :style="{ minWidth: '134px' }"
                />               
              </t-form-item>
            </t-col>
            <t-col :flex="1">
              <t-form-item label="运行结果" name="status">
                <t-select
                  v-model="formData.last_status"
                  class="form-item-content"
                  :options="CASE_STATUS_OPTIONS"
                  placeholder="请选择运行结果"
                  id="status"
                  :style="{ minWidth: '134px' }"
                />
              </t-form-item>
            </t-col>
            <t-col :flex="1">
              <t-form-item label="创建人" name="user">
                <t-select
                  v-model="formData.create_user"
                  class="form-item-content"
                  placeholder="请选择用户"
                  @focus="getUserList"
                  :options="userList"
                  :keys="{ label: 'real_name', value: 'username' }"
                  multiple
                  :minCollapsedNum="3"
                  @change="handleChangeCreateUser"
                  id="user"
                  :style="{ minWidth: '134px' }"
                />               
              </t-form-item>
            </t-col>
            <t-col :flex="1">
              <t-form-item label="标签" name="tags">
                <t-select
                  v-model="formData.testcase_tags"
                  :tag-input-props="{ excessTagsDisplayType }"
                  class="form-item-content"
                  placeholder="请选择标签"
                  @focus="getTestCaseTags"
                  :options="testCaseTags"
                  :keys="{ label: 'tag_name', value: 'tag_id' }"
                  multiple
                  :minCollapsedNum="3"
                  @change="handleChangeTags"
                  id="tags"
                  :style="{ minWidth: '400px' }"
                />               
              </t-form-item>
            </t-col>

            <!-- <t-col :flex="1">
              <t-form-item label="标签2" name="tags2">
                <t-select-input
                  :input-value:sync="inputValue"
                  :value="tagValue"
                  :allow-input="allowInput"
                  :placeholder="allowInput ? '请选择或输入' : '请选择'"
                  :tag-input-props="{ excessTagsDisplayType }"
                  :popup-props="{
                    overlayInnerClassName: ['narrow-scrollbar'],
                    overlayInnerStyle: {
                      maxHeight: '280px',
                      overflowY: 'auto',
                      overscrollBehavior: 'contain',
                      padding: '6px',
                    },
                  }"
                  clearable
                  multiple
                  @focus="handleFocus"
                  @blur="handleBlur"
                  @tag-change="onTagChange"
                  @input-change="onInputChange"
                  @clear="handleClear"
                  @enter="handleEnter"
                  @mouseenter="handleMouseenter"
                  @change="handleChange"
                >
                  <template #panel>
                    <t-checkbox-group
                      v-if="testCaseTags.length"
                      :value="checkboxValue"
                      :options="testCaseTags"
                      :keys="{ label: 'tag_name', value: 'tag_id' }"
                      class="tdesign-demo__panel-options-multiple"
                      @change="onCheckedChange"
                    />
                    <div v-else class="tdesign-demo__select-empty-multiple">暂无数据</div>
                  </template>
                  <template #suffixIcon>
                    <chevron-down-icon />
                  </template>
                </t-select-input>
              </t-form-item>
            </t-col> -->
          </t-row>
        </t-col>



        <t-col :span="2" class="operation-container">
          <t-button theme="primary" type="submit" :style="{ marginLeft: '8px' }">查询</t-button>
          <t-button type="reset" variant="base" theme="default">重置</t-button>
        </t-col>
      </t-row>
      <t-row style="margin-left: auto; margin-top: 20px;">
        <t-col :span="1.5" class="operation-ad-container">
          <t-button @click="createTestCase" theme="primary" :style="{ margin: '8px'}">新建用例</t-button>
          <t-button @click="runTestCase" theme="primary" :style="{ margin: '8px'}" :disabled="!selectedRowKeys.length">执行用例</t-button>
          <t-button @click="createTestPlan" theme="primary" :style="{ margin: '8px'}" :disabled="!selectedRowKeys.length">生成计划</t-button>
          <t-button @click="deleteTestCase" variant="base" theme="warning" :style="{ margin: '8px'}" :disabled="!selectedRowKeys.length">删除测试用例</t-button>
          <p v-if="!!selectedRowKeys.length" class="selected-count" >已选{{ selectedRowKeys.length }}项</p>
        </t-col>
      </t-row>
    </t-form>
    <div class="table-container">
      <div class="operation-container">
        <t-button @click="columnControllerVisible = true">显示列配置弹窗</t-button>
      </div>
        <t-form labelWidth="150">
          <t-form-item>
            <t-input-adornment prepend="filter:">
              <t-input v-model="casePath" @change="caseInput" />
            </t-input-adornment>
          </t-form-item>
        </t-form>

        <t-space :size="32" class="tdesign-tree-demo">
          <t-tree 
          :data="TESTCASE_PATH" 
          hover 
          :expandLevel=1 
          :filter="caseFilter" 
          :checkable="checkable" 
          v-model="value" 
          :lazy="false" 
          style="width:250px;margin-top:20px"
          @change="treeChange"
          @click="treeClick"
          :label="label"
          />
          <t-table
        row-key="rowIndex"
        :data="treeData"
        :columns="columns"
        :rowKey="rowKey"
        :verticalAlign="verticalAlign"
        :hover="hover"
        :pagination="pagination"
        :selected-row-keys="selectedRowKeys"
        @page-change="rehandlePageChange"
        @change="rehandleChange"
        @select-change="rehandleSelectChange"
        :loading="dataLoading"
        :headerAffixedTop="true"
        :sort="sort"
        :multipleSort="allowMultipleSort"
        @sort-change="sortChange"
        @data-change="dataChange"
        :headerAffixProps="{ offsetTop, container: getContainer }"
        :displayColumns.sync="displayColumns"
        :columnControllerVisible.sync="columnControllerVisible"
        :columnController="{
        fields: this.controlColum,
        dialogProps: { preventScrollThrough: true },
        hideTriggerButton: true,
        }"
        :table-layout="tableLayout"
      >
      <template #status="row">
        <p class="status" :class="['', 'warning', 'unhealth'][row.last_status]">
              {{ ['健康', '警告', '异常'][row.last_status] }}
            </p>
      </template>
      <template #op="slotProps">
          <a class="t-button-link" @click="runTestCaseSingle(slotProps)">运行</a>
          <a class="t-button-link" @click="viewTestCase(slotProps)">查看</a>
          <a class="t-button-link" variant="outline" @click="modifyDialog(slotProps)">编辑</a>
          <a class="t-button-link" @click="handleClickDelete(slotProps)">删除</a>
        </template>
      </t-table>
      </t-space>


      <t-dialog
        header="确认删除当前所选用例？"
        :body="confirmBody"
        :visible.sync="confirmVisible"
        @confirm="onConfirmDelete"
        :onCancel="onCancel"
      >
      </t-dialog>
      <!-- <t-dialog
        header="测试用例"
        :body="confirmBody"
        :visible.sync="showDialogView"
      >
      <p>ssssssss</p>
      </t-dialog> -->
    </div>
  </div>
  
</template>
<script lang="jsx">
import { prefix } from '@/config/global';
// import Trend from '@/components/trend/index.vue';
import modifyDialogComp from './ModifyDialogComp.vue';
import addDialogComp from './AddDialogComp.vue';
import RunDialogComp from './RunDialogComp.vue';
import ViewDialogComp from './ViewDialogComp.vue';
import TestPlanDialogComp from './TestPlanDialogComp.vue';
import { ErrorCircleFilledIcon, CheckCircleFilledIcon, CloseCircleFilledIcon, CaretDownSmallIcon, ChevronDownIcon} from 'tdesign-icons-vue';
import { TESTCASE_PATH } from '@/service/service-detail'
import { getTestCaseList, operateTestCase, getTags, getSprints, getUserList} from '@/api/requestApi'

import {
  CASE_STATUS,
  CASE_STATUS_OPTIONS,
  MODULES_OPTIONS,
  TESTCASE_PRIORITY_OPTIONS,
} from '@/constants';


const INITIAL_FORM_DATA = {
  testcase_id:'',
  testcase_name: '',
  module: '',
  testcase_version: '',
  // testcase_tags: [],
  priority: '',
  last_status: '',
  create_user: '',
  create_time: '',
};
const staticColumn = ['row-select', 'testcase_id', 'testcase_name', 'op'];
const controlColum = ['testcase_tags', 'module', 'testcase_version', 'priority', 'last_status', 'create_user', 'create_time', 'update_user', 'update_time'];

export default {
  name: 'list-table',
  components:{
    modifyDialogComp,
    addDialogComp,
    RunDialogComp,
    ViewDialogComp,
    TestPlanDialogComp,
    // TestPlanDialog,
  },
  inject: ['reload'],
  
  data() {
    return {
      CASE_STATUS,
      CASE_STATUS_OPTIONS,
      MODULES_OPTIONS,
      TESTCASE_PRIORITY_OPTIONS,
      TESTCASE_PATH,
      testCaseVersion: [],
      testCaseTags: [],
      casePath: '',
      caseFilter: null,
      userList:[],
      deleteId:'',
      deleteIds:[],
      modifyData:{},
      prefix,
      formData: {...INITIAL_FORM_DATA},
      // FORM_RULES: {...FORM_RULES},
      data: [],
      selectedRowKeys: [],
      dataLoading: false,
      // value1: 'first',
      excessTagsDisplayType: 'scroll',
      allowInput: true,
      creatable: false, // 不允许创建新条目
      inputValue: '',
      sort: [
        {
          sortBy: 'id',
          descending: false,
        },
        {
          sortBy: 'testcase_version',
          descending: false,
        },
        {
          sortBy: 'create_time',
          descending: true,
        },
        {
          sortBy: 'update_time',
          descending: false,
        },
      ],
      singleSort: {
        sortBy: 'status',
        descending: true,
      },
      multipleSorts: [
        {
          sortBy: 'status',
          descending: true,
        },
      ],
      allowMultipleSort: false,
      globalLocale: {
        table: {
          sortIcon: (h) => h && <CaretDownSmallIcon size="10px" />,
        },
      },
      // 动态配置列
      columnControllerVisible: false,
      displayColumns: staticColumn.concat(['testcase_tags', 'module', 'testcase_version', 'priority', 'last_status', 'create_user']),
      controlColum,
      tableLayout: 'fixed',
      leftFixedColumn: 2,
      rightFixedColumn: 1,
      columns: [
        { colKey: 'row-select', type: 'multiple', width: 64, fixed: 'left' },
        {
          title: 'ID',
          width: 50,
          ellipsis: true,
          colKey: 'testcase_id',
          fixed: 'left',
          // sortType: 'all',
          // sorter: (a, b) => a.testcase_id - b.testcase_id,
        },
        {
          title: '用例名称',
          width: 250,
          align: 'left',
          ellipsis: true,
          colKey: 'testcase_name',
          fixed: this.leftFixedColumn >= 2 ? 'left' : undefined,
        },
        { 
          title: '标签', 
          colKey: 'testcase_tags', 
          width: 100, 
          cellipsis: true,
          cell: (h, {row}) => {
            const tagStr = row.testcase_tags.toString();
            return (
              <div>{tagStr}</div>
            )}
        },

        { 
          title: '模块', 
          colKey: 'module', 
          width: 60, 
          ellipsis: true,
          cell: (h, {row}) => {
            const moduleListMap = {
              // -1: { value: -1, label: '虚拟机', checked: false},
              0: { value: 0, label: '虚拟机'},
              1: { value: 1, label: '合约'},
              2: { value: 2, label: '共识'},
              3: { value: 3, label: '权限'},
              4: { value: 4, label: '交易池'},
              5: { value: 5, label: '网络'},
              6: { value: 6, label: '权限'},
              99: { value: 99, label: '其他'},
            };
            return (
              <div>{moduleListMap[row.module].label}</div>             
            );
          }, 

        },
        { title: '版本', 
          colKey: 'testcase_version', 
          width: 80, 
          ellipsis: true,
          cell: (h, {row}) => {
            const versionListMap = this.testCaseVersion;
            return (
              <div>
                {versionListMap[row.testcase_version-1].sprint_name}
              </div>
            );
          },
          // sortType: 'all',
          // sorter: (a, b) => a.testcase_version - b.testcase_version,
        },
        { 
          title: '优先级', 
          colKey: 'priority', 
          width: 80, 
          ellipsis: true,
          cell: (h, {row}) => {
            const priorityListMap = {
              0: { value: 0, label: 'High', checked: false},
              1: { value: 1, label: 'Normal', checked: false},
              2: { value: 2, label: 'Low', checked: false},
              3: { value: 5, label: 'BVT', checked: false},
            };
            return (
              <div>
                {priorityListMap[row.priority].label}
              </div>
            );
          }, 
        },
        { 
          title: '运行结果', 
          colKey: 'last_status', 
          width: 100, 
          cell: (h, {row}) => {
            const statusNameListMap = {
              0: { label: '未执行', theme: 'warning', icon: <ErrorCircleFilledIcon /> },
              1: { label: '执行通过', theme: 'success', icon: <CheckCircleFilledIcon /> },
              2: { label: '执行失败', theme: 'danger', icon: <CloseCircleFilledIcon /> },
            };
            return (
              <t-tag shape="round" theme={statusNameListMap[row.last_status].theme} variant="light-outline">
                {statusNameListMap[row.last_status].icon}
                {statusNameListMap[row.last_status].label}
              </t-tag>
            );
          }, 
        },
        {
          title: '创建人',
          width: 80,
          ellipsis: true,
          colKey: 'create_user',
        },
        {
          title: '创建时间',
          width: 50,
          ellipsis: true,
          colKey: 'create_time',
          // sortType: 'all',
          // sorter: (a, b) => b.create_time - a.create_time,
        },
        {
          title: '更新人',
          width: 50,
          ellipsis: true,
          colKey: 'update_user',
        },
        {
          title: '更新时间',
          width: 50,
          ellipsis: true,
          colKey: 'update_time',
          // sortType: 'all',
          // sorter: (a, b) => b.update_time - a.update_time,
        },    
        {
          align: 'left',
          fixed: 'right',
          width: 200,
          colKey: 'op',
          title: '操作',
        },
      ],
      rowKey: 'testcase_id',
      verticalAlign: 'top',
      showDialog: false, // 控制编辑弹窗的现实与隐藏
      showDialogAdd: false, // 控制新增弹窗的现实与隐藏
      showDialogRun: false, // 控制运行弹窗的现实与隐藏
      showDialogView: false, // 控制查看日志弹窗的现实与隐藏
      showDialogTestplan: false,// 控制生成测试计划弹窗的现实与隐藏
      bordered: true,
      hover: true,
      rowClassName: (rowKey) => `${rowKey}-class`,
      // 与pagination对齐
      pagination: {
        defaultPageSize: 20,
        total: 100,
        defaultCurrent: 1,
      },
      confirmVisible: false,
      confirmVisible1: false,
      confirmVisible3: false,
      testPlanName: '',
      deleteIdx: -1,
      checkable: true,
      value: ['3.4'],
      treeData:[],
    };
  },

  computed: {
    confirmBody() {
      if (this.deleteIdx > -1) {
        // console.log('data--->', this.data[this.deleteIdx], this.deleteIdx)
        // const testcaseid = row.testcase_id
        const { testcase_name } = this.data.filter((row) => row.testcase_id === this.deleteIdx)[0];     
        return `删除后，${testcase_name}的用例信息将被清空，且无法恢复`;
      }
      return '所选测试用例批量删除后将无法恢复';
    },
    offsetTop() {
      return this.$store.state.setting.isUseTabsRouter ? 48 : 0;
    },
    checkboxValue() {
      const arr = [];
      console.log('testCaseTags--->', this.testCaseTags);
      const list = this.testCaseTags;
      // 此处不使用 forEach，减少函数迭代
      for (let i = 0, len = list.length; i < len; i++) {
        if (list[i].tag_id){
          arr.push(list[i].tag_id);
        }
      }
      console.log('arr--->', arr);
      return arr;
    },
  },
  watch: {
    allowMultipleSort: {
      immediate: true,
      handler(val) {
        this.sort = val ? this.multipleSorts : this.singleSort;
      },
    },
    '$route': '/function/testcase',
  },
  // created () {
  //   this.getTestCaseVersion();
  // },
  mounted() {   
    this.dataLoading = true;
    // getTestCaseList()
    this.$request
      .get(getTestCaseList())
      .then((res) => {
        // console.log(res)
        if (res.data.code === '000') {
          // this.$message.success(res.data.msg);
          const list = res.data.data;
          this.data = list;
          this.treeData = this.data
          // console.log(this.data)
          this.pagination = {
            ...this.pagination,
            total: list.length,
          };
        } else {
          this.$message.error(res.data.msg);
        }   
      })
      .catch((e) => {
        this.$message.error('系统异常');
        console.log(e);
      })
      .finally(() => {
        this.dataLoading = false;
      });
    this.getTestCaseVersion();
    // this.getTestCaseTags();
    // this.getUserList()
  },
  
  methods: {
    getContainer() {
      return document.querySelector('.tdesign-starter-layout');
    },
    
    onReset() {
      this.formData.testcase_id = '';
      this.formData.testcase_name = '';
      this.formData.testcase_tags = '';
      this.formData.module = '';
      this.formData.testcase_version = '';
      this.formData.priority = '';
      this.formData.last_status = '';
      this.formData.create_user = '';
    },
    onSubmit() {
      // console.log('查询->', this.formData);
      this.dataLoading = true;
      let url = getTestCaseList();
      Object.keys(this.formData).forEach(key =>{
        // if (key === 'testcase_tags' && this.formData[key].length > 0){
        // if (key !== '') {
        if (this.formData[key].length > 0){
          // 如果该项的obj不为空（等于0也可以），并且是第一个不为空的参数时，直接进行拼接，不用加&
          if(url==='/api/query/testcase_list' && this.formData[key] || url==='/api/query/testcase_list' && this.formData[key]===0){
            url=`${url}?${key}=${this.formData[key]}`
          // 如果该项的obj不为空（等于0也可以），但不是第一个不为空的参数时，加&进行拼接
          } else if(url!=='/api/query/testcase_list' && this.formData[key] || url!=='/api/query/testcase_list' && this.formData[key]===0){
            url=`${url}&${key}=${this.formData[key]}`
          }
        }
        
        // }
        // 如果该项的obj不为空（等于0也可以），并且是第一个不为空的参数时，直接进行拼接，不用加&
        // if(url==='/api/query/testcase_list?' && this.formData[key] || url==='/api/query/testcase_list?' && this.formData[key]===0){
        //   url=`${url}${key}=${this.formData[key]}`
        //   // 如果该项的obj不为空（等于0也可以），但不是第一个不为空的参数时，加&进行拼接
        // } else if(url!=='/api/query/testcase_list?' && this.formData[key] || url!=='/api/query/testcase_list?' && this.formData[key]===0){
        //   url=`${url}&${key}=${this.formData[key]}`
        // }
      })
      // getTestCaseList(url)
      this.$request
        .get(url)
        .then((res) => {
          if (res.data.code === '000') {
            // this.$message.success(res.data.msg);
            const list = res.data.data;
            this.treeData = list;
            console.log('data--->',this.data)
            this.pagination = {
              ...this.pagination,
              total: list.length,
            };
          } else {
            this.$message.error(res.data.msg);
          }   
        })
        .catch((e) => {
          this.$message.error('系统异常');
          console.log(e);
        })
        .finally(() => {
          this.dataLoading = false;
        });

    },
    rehandlePageChange(curr, pageInfo) {
      console.log('分页变化', curr, pageInfo);
    },
    rehandleChange(changeParams, triggerAndData) {
      console.log('统一Change', changeParams, triggerAndData);
    },
    // rehandleSelectChange(selectedRowKeys) {
    //   this.selectedRowKeys = selectedRowKeys;
    // },
    rehandleSelectChange(selectedRowKeys,value) {
      this.selectedRowKeys = selectedRowKeys;
      console.log(selectedRowKeys,value);
    },
    handleClickConn({slotProps}) {
      console.log(slotProps.rowIndex);
    },
    addOrUpdateRefresh() {
      console.log("text, row");
    },
    modifyDialog(slotProps) {
      this.showDialog = true;
      this.$nextTick(()=>{     
        this.$refs.dialog.init(slotProps.row);
      })
    },
    
    deleteTestCase() {
      // console.log(this.selectedRowKeys)
      // this.selectedIdx = this.selectedRowKeys
      this.confirmVisible = true;
    },
    handleClickDelete(slotProps) {
      console.log(slotProps)
      this.deleteIdx = slotProps.row.testcase_id;
      this.confirmVisible = true;
    },
    onConfirmDelete() {
      // 真实业务请发起请求
      let ids = [];
      const reqParam = {"ids": [],"op_type": "0","param": {}}
      this.confirmVisible = false;
      this.dataLoading = true; 
      // console.log("打印下单选deleteIdx",this.deleteIdx)
      if (this.deleteIdx > -1){
        ids.push(this.deleteIdx)
        // console.log("打印下单选ids",ids)
      } else {
        // ids = Array.from(Object.values(this.selectedRowKeys), x=>x);
        const ids = []
        // eslint-disable-next-line array-callback-return
        this.selectedRowKeys.map(x=>{
          ids.push(this.data[x-1].testcase_id)
        });
        ids.forEach(x=>{
          const {testcase_name, testcase_id} = this.data[x-1]
          console.log('选中用例为：',testcase_name, testcase_id)
        })
        // console.log('ids----->', ids, this.data)
        // ids = Object.values(this.selectedRowKeys)
        // console.log("打印下多;选ids",ids)
      }
      reqParam.ids = ids.map(String);
      reqParam.op_type = '0';
      // console.log(ids.length)
      if (ids.length > 0) {
        this.$request
          .post(operateTestCase(), reqParam)
          .then((res) => {
            if (res.data.code === "000") {
              this.$message.success('测试用例删除成功');
            }
          })
          .catch((e) => {
            console.log(e);
          })
          .finally(() => {
            this.dataLoading = false;
          });
      }
      this.resetIdx();
    },
    createTestCase() {
      this.showDialogAdd = true;
      // console.log("创建新测试用例");
    },
    createTestPlan() {
      this.showDialogTestplan = true;
      
      this.confirmVisible = false;
      // const testcase_id = Array.from(Object.values(this.selectedRowKeys), x=>x);
      const testcase_ids = []
      // eslint-disable-next-line array-callback-return
      this.selectedRowKeys.map(x=>{
        testcase_ids.push(this.data[x-1].testcase_id)
      });
      testcase_ids.forEach(x=>{
        const {testcase_name, testcase_id} = this.data[x-1]
        console.log('选中用例为：',testcase_name, testcase_id)
      })
      // ids = ids.map(String);
      // ids = Object.values(this.selectedRowKeys)
      console.log("打印下多;选ids",testcase_ids)
      this.$nextTick(()=>{     
        this.$refs.dialogtestplan.init(testcase_ids);
      });
    },
    // 批量执行用例前组装用例数据，打开用例执行对话框
    runTestCase() {
      this.showDialogRun = true;
      const testCaseList = [];
      const ids = Array.from(Object.values(this.selectedRowKeys), x=>x);
      Object.keys(ids).forEach(key => {
        const selectTestCase = {'testcaseid': '', 'testcasename': '', 'testcasegitaddr': ''};
        const testcaseid = ids[key];
        const testcasename =  this.data[key].testcase_name;
        const testcasegitaddr = this.data[key].git_addr;
        selectTestCase.testcaseid = testcaseid;
        selectTestCase.testcasename = testcasename;
        selectTestCase.testcasegitaddr = testcasegitaddr;
        testCaseList.push(selectTestCase);
      })      
      this.$nextTick(()=>{
        this.$refs.dialogrun.initBatch(testCaseList);
      });
    },
    // 单独执行用例
    runTestCaseSingle(slotProps) {
      this.showDialogRun = true;
      console.log("单条执行测试用例", slotProps)
      this.$nextTick(()=>{      
        this.$refs.dialogrun.init(slotProps.row);
      });
    },
    // 查看用例执行日志和脚本内容
    viewTestCase(slotProps) {
      const reqParam = {"ids": [], "param": [{}], "op_type": ''};
      const viewData = {'testcase_script':'', 'testcase_log':''}
      reqParam.ids.push(slotProps.row.testcase_id.toString())
      // 获取脚本内容，op_type = "4"
      reqParam.op_type = "4";
      console.log("提交的表单内容->", reqParam);
      this.$request
        .post(operateTestCase(),reqParam)
        .then((res) => {
          if (res.data.code === '000') {
            viewData.testcase_script = res.data.data
          }
        })
        .catch((e) => {
          console.log(e);
        })
        .finally(() => {
          this.dataLoading = false;
        });
      // 获取用例执行日志，op_type = "5"
      reqParam.op_type = "5";
      console.log("提交的表单内容->", reqParam);
      this.$request
        .post(operateTestCase(), reqParam)
        .then((res) => {
          if (res.data.code === '000') {
            viewData.testcase_log = res.data.data
          }
        })
        .catch((e) => {
          console.log(e);
        })
        .finally(() => {
          this.dataLoading = false;
        });
      this.showDialogView = true;
      this.$nextTick(()=>{      
        this.$refs.dialogview.init(viewData);
      });
    },
    modifyTestCase() {
      console.log("修改测试用例")
    },
    onCancel() {
      this.resetIdx();
    },
    resetIdx() {
      this.deleteIdx = -1;
    },
    // 除了监听 sortChange 事件调整排序，也可以监听 change 事件
    sortChange(sort, options) {
      console.log('sort-change', sort, options);
      // 受控操作当中，this.sort 和 this.data 的赋值都是必须
      this.sort = sort;
      // this.data = options.currentDataSource;
    },
    dataChange(data) {
      // 除了 sortChange，也可以在这里对 data.value 进行赋值
      this.data = data;
      console.log('data-change', data);
    },
    // 处理字典
    // mapData(data) {
    //   const mappedData = { ...data };
    //   const sexMap = { '1': '男', '2': '女' };
    //   const typeMap = { '1': '类型1', '2': '类型2', '3': '类型3' };
    //   mappedData.sex = sexMap[data.sex];
    //   mappedData.type = typeMap[data.type];

    //   return mappedData;
    // }
    // 获取版本
    getTestCaseVersion(){
      getSprints()
        .then((res) => {
          if (res.data.code === '000') {
            const list = res.data.data;   
            this.testCaseVersion = list;
            console.log('testcaseversion--->',this.testCaseVersion)
          }
        })
        .catch((e) => {
          console.log(e);
        })
        .finally(() => {
          this.dataLoading = false;
        });
        
    },
    // 获取标签
    getTestCaseTags(){
      getTags()
        .then((res) => {
          if (res.data.code === '000') {
            const list = res.data.data;      
            this.testCaseTags = list;
            console.log('testcasetag',this.testCaseTags)
          }
        })
        .catch((e) => {
          console.log(e);
        })
        .finally(() => {
          this.dataLoading = false;
        });
    },
    // 获取创建人
    getUserList(){
      this.$request
        .get(getUserList())
        .then((res) => {
          if (res.data.code === '000') {
            const list = res.data.data;      
            this.userList = list;
          }
        })
        .catch((e) => {
          console.log(e);
        })
        .finally(() => {
          this.dataLoading = false;
        });
    },
    handleChangeModule(...args) {
      console.log('change', ...args);
    },
    handleChangePriority(...args) {
      console.log('change', ...args);
    },
    handleChangeVersion(...args) {
      console.log('change', ...args);
    },
    handleChangeTags(...args) {
      console.log('change', ...args);
    },
    handleChangeCreateUser(...args) {
      console.log('change', ...args);
    },
   
    // valueDisplay(h, { onClose, displayValue }) {
    //   if (!(displayValue instanceof Array)) 
    //     return;
    //   // return displayValue.map((item, index) => (
    //   //   <t-tag
    //   //     key={index}
    //   //     closable={true}
    //   //     onClose={(context) => {if(context.e){context.e.stopPropagation();}onClose(index);}}
    //   //   >
    //   //     {item.label}
    //   //   </t-tag>
    //   // ));
    // },
    // sleep
    sleep(ms) {
      return new Promise(resolve => setTimeout(resolve, ms));
    },
    async flushTable(){
      await this.sleep(2000)
      this.reload();
    },
    handleFocus(value, context) {
      console.log('focus', value, context);
    },
    handleBlur() {
      console.log('Blur');
    },
    handleClear() {
      console.log('Clear');
    },
    handleEnter() {
      console.log('Enter');
    },
    handleMouseenter() {
      console.log('Mouseenter');
    },
    handleChange() {
      console.log('Change');
    },
    onCheckedChange(val, { current, type }) {
      console.log('current-->', current);
      // current 不存在，则表示操作全选
      if (!current) {
        this.tagValue = type === 'check' ? this.testCaseTags.slice(1) : [];
        return;
      }
      // 普通操作
      if (type === 'check') {
        const testCaseTag = this.testCaseTags.find((t) => t.tagValue === current);
        this.tagValue.push(testCaseTag);
      } else {
        this.tagValue = this.tagValue.filter((v) => v.tagValue !== current);
      }
    },
    onTagChange(currentTags, context) {
      console.log(currentTags, context);
      const { trigger, index, item } = context;
      if (trigger === 'clear') {
        this.tagValue = [];
      }
      if (['tag-remove', 'backspace'].includes(trigger)) {
        this.tagValue.splice(index, 1);
      }
      // 不允许创建新条目
      // if (this.creatable && trigger === 'enter') {
      //   const current = { label: item, value: item };
      //   this.value.push(current);
      //   const newOptions = this.options.concat(current);
      //   this.options = newOptions;
      //   this.inputValue = '';
      // }
    },
    onInputChange(val, context) {
      console.log('val-->', val, context);
    },
    load(node) {
      return new Promise((resolve) => {
        setTimeout(() => {
          let nodes = [];
          if (node.level < 2) {
            nodes = [
              {
                label: `${node.label}.1`,
                value: `${node.value}.1`,
                children: true,
              },
              {
                label: `${node.label}.2`,
                value: `${node.value}.2`,
                children: true,
              },
            ];
          }
          resolve(nodes);
        }, 1000);
      });
    },
    caseInput(state) {
      console.info('case input:', state);
      if (this.casePath) {
        // 存在过滤文案，才启用过滤
        this.caseFilter = (node) => {
          const rs = node.data.label.indexOf(this.casePath) >= 0;
          // 命中的节点会强制展示
          // 命中节点的路径节点会锁定展示
          // 未命中的节点会隐藏
          return rs;
        };
      } else {
        // 过滤文案为空，则还原 tree 为无过滤状态
        this.caseFilter = null;
      }
    },
    treeClick(context) {
      console.info('onClick:', context);
      const { node } = context;
      console.info(node.value, 'checked:', node.checked);
    },
    treeChange(checked, context) {
      console.info('onChange:', checked, context);
      // const { node } = context;
      // console.info('path--->', node.value, 'checked:', node.checked);
      this.treeData = this.data
      if (checked.length !== 0 ) {
        this.treeData = this.data.filter(item => checked.some(node => item.script_path.includes(node)))
      }
      console.log('treeData--->', this.treeData)
    },
    label(createElement, node) {
      return `${node.label}`;
    },
  },
 
};
</script>

<style lang="less" scoped>
@import '@/style/variables.less';

.form-item-content {
  width: 50%;
}

.selected-count {
    display: inline-block;
    margin-left: var(--td-comp-margin-s);
    color: var(--td-text-color-secondary);
  }
.operation-container {
  display: flex;
  justify-content: flex-end;
  align-items: center;
}

.operation-ad-container {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  margin-left: -8px;
}

.tdesign-demo__panel-options-multiple {
  width: 100%;
  padding: 0;
  display: flex;
  flex-direction: column;
  gap: 2px;
}
.tdesign-demo__panel-options-multiple .t-checkbox {
  display: flex;
  border-radius: 3px;
  line-height: 22px;
  cursor: pointer;
  padding: 3px 8px;
  color: var(--td-text-color-primary);
  transition: background-color 0.2s linear;
  white-space: nowrap;
  word-wrap: normal;
  overflow: hidden;
  text-overflow: ellipsis;
  margin: 0;
}
.tdesign-demo__panel-options-multiple .t-checkbox:hover {
  background-color: var(--td-bg-color-container-hover);
}

.tdesign-tree-demo {
  line-height: 24px;
  text-indent: 1em;
}
</style>
